import requests
from bs4 import BeautifulSoup

from website.base_model import ProductRawModel

BASE_URL = "https://tzybiotech.cn"

headers = {
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "accept-language": "zh-CN,zh;q=0.9",
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36",
}

def get_des_url(pro_code: str) -> str | None:
    """
    获取该货号的商品详情链接
    """
    url = f"{BASE_URL}/index/search.html"
    params = {"key": pro_code}
    try:
        response = requests.get(url, headers=headers, params=params)
        response.raise_for_status()
    except requests.RequestException as e:
        print(e)
        return None

    soup = BeautifulSoup(response.text, "html.parser")
    pro_dom = soup.find("div", class_="textBox")
    if pro_dom:
        a_tag = pro_dom.find("a")  # type: ignore
        if a_tag and "href" in a_tag.attrs:
            return BASE_URL + a_tag["href"]

    return None


def get_prodes_dom(url: str) -> BeautifulSoup:
    """
    获取商品详情dom结构
    """
    response = requests.get(url, headers=headers)
    resp_dom = BeautifulSoup(response.text, "html.parser")
    return resp_dom


def get_prodes_name(resp_dom: BeautifulSoup) -> str:
    """
    获取商品名称
    """
    title_dom = resp_dom.find("div", class_="proTop")
    if title_dom:
        title = title_dom.find("h3")  # type: ignore
        if title:
            return title.get_text(strip=True)
    return ""


def get_prodes_img(resp_dom: BeautifulSoup) -> str:
    """
    获取商品详情图片
    """
    img_dom = resp_dom.find("div", class_="picBoxCon")
    if img_dom:
        img_tag = img_dom.find("em", class_="bgCover")  # type: ignore
        if img_tag and "data-src" in img_tag.attrs:
            return BASE_URL + img_tag["data-src"]
    return ""


def get_prodes_text(resp_dom: BeautifulSoup) -> str:
    """
    获取商品描述信息
    """
    text_dom = resp_dom.find("div", class_="proCenter")
    if text_dom:
        return str(text_dom)  # 提取文本并去除多余空白
    return ""


def raw_proinfo(procode: str) -> ProductRawModel | None:
    """商品原始信息

    Args:
        procode (str): 商品货号
    """
    des_url = get_des_url(procode)

    if des_url:
        prodes_dom = get_prodes_dom(des_url)

        return {
            "code": procode,
            "name": get_prodes_name(prodes_dom),
            "photos": get_prodes_img(prodes_dom),
            "desc": get_prodes_text(prodes_dom),
        }
    return None
